import 'package:flutter/material.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import 'package:get/get.dart';
import 'package:mziot/app/config/design.dart';
import 'package:mziot/app/modules/home/controllers/home_controller.dart';
import 'package:mziot/app/routes/app_pages.dart';
import 'package:mziot/app/tools/tools.dart';
import 'package:mziot/generated/assets.dart';
import 'package:mziot/generated/locales.g.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class GroupListView extends GetView<HomeController> {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(bottom: 16),
      padding: EdgeInsets.symmetric(horizontal: 12),
      child: Obx(() {
        int count = controller.groupList.value.length;
        return SmartRefresher(
          controller: controller.refreshController,
          onRefresh: () => controller.refreshAction(),
          onLoading: () => controller.loadMore(),
          child: ListView.builder(
            itemCount: count + 1,
            itemBuilder: (ctx, index) {
              if (index == count) {
                return _emptyView;
              }

              return _deviceItem(index);
            },
          ),
        );
      }),
    );
  }

  Widget _deviceItem(int index) {
    return GestureDetector(
      onTap: () {
        bool lockStatus = controller.groupList.value[index].isLock.value;
        if (lockStatus) {
          return;
        }
        controller.toLighting(index);
      },
      onLongPress: () {
        bool lockStatus = controller.groupList.value[index].isLock.value;
        if (lockStatus) {
          return;
        }
        controller.deleteConfirm(controller.groupList.value[index].id);
      },
      child: Container(
        margin: EdgeInsets.only(top: 16),
        padding: EdgeInsets.only(top: 16, left: 16),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          color: Colors.white,
          image: DecorationImage(image: AssetImage(Assets.imagesGroupBack), fit: BoxFit.fill),
        ),
        child: Column(
          children: [
            _topView(index),
            SizedBox(height: 12),
            _bottomView(index),
          ],
        ),
      ),
    );
  }

  Widget _topView(int index) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Image.asset(
          Assets.imagesDeviceGroupIcon,
          width: 60,
          height: 60,
        ),
        Spacer(),
        _markView(index),
        SizedBox(width: 8),
        _progress(index),
      ],
    );
  }

  Widget _bottomView(int index) {
    var item = controller.groupList.value[index];
    return Row(
      children: [
        Expanded(
          child: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              Get.toNamed(
                Routes.DEVICE_MANAGER,
                arguments: {'group': true, 'add': false, 'data': controller.groupList.value[index]},
              )?.then((value) {
                controller.refreshAction();
              });
            },
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      item.groupName ?? '-',
                      style: MFont.semi_Bold15.apply(color: MColor.xFF333333),
                    ),
                    SizedBox(width: 5),
                    Icon(
                      Icons.arrow_forward_ios_outlined,
                      size: 15,
                      color: MColor.xFF333333,
                    ),
                  ],
                ),
                Text(
                  item.sceneName ?? '-',
                  style: MFont.regular11.apply(color: MColor.xFF999999),
                ),
              ],
            ),
          ),
        ),
        SizedBox(width: 8),
        _toolView(index),
      ],
    );
  }

  Widget _checkView(int index) {
    return Obx(() {
      bool selected = controller.groupList.value[index].isSelected.value;

      return Container(
        padding: EdgeInsets.all(7.5),
        decoration: BoxDecoration(
          color: selected ? MColor.skin : MColor.xFFEEEEEE,
          borderRadius: BorderRadius.circular(15),
        ),
        child: Icon(
          Icons.check,
          size: 15,
          color: selected ? Colors.white : MColor.xFFEEEEEE,
        ),
      );
    });
  }

  Widget _toolView(int index) {
    return Obx(() {
      if (index >= controller.groupList.length) {
        return Container();
      }
      bool lockStatus = controller.groupList.value[index].isLock.value;
      bool isClose = controller.groupList.value[index].closeState.value;

      Widget iconButton(String name, int buttonIndex) {
        return Container(
          padding: EdgeInsets.only(bottom: 10, right: 5),
          child: IconButton(
            onPressed: () {
              if (buttonIndex == 0) {
                Get.toNamed(Routes.GROUP_LIST, arguments: {
                  'groupId': controller.groupList.value[index].id,
                  'name': controller.groupList.value[index].groupName
                })?.then((value) {
                  Get.back();
                });
              } else {
                throttle(() {
                  controller.fetchSwitchDevices(index, false,
                      group: controller.groupList.value[index]);
                });
              }
            },
            iconSize: 40,
            icon: Opacity(
              opacity: (lockStatus && buttonIndex == 1) ? 0.5 : 1,
              child: Image.asset(
                name,
                width: 40,
                height: 40,
              ),
            ),
            constraints: BoxConstraints(maxHeight: 50),
          ),
        );
      }

      return Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          iconButton(Assets.imagesDeviceList, 0),
          IgnorePointer(
            ignoring: lockStatus,
            child: iconButton(
              !isClose ? Assets.imagesDeviceOpen : Assets.imagesDeviceClose,
              1,
            ),
          ),
        ],
      );
    });
  }

  Widget _markView(int index) {
    String? image;
    bool? lockStatus = controller.groupList.value[index].lockStatus;

    if (lockStatus == true) {
      image = Assets.imagesSceneLock;
    }

    if (image == null) {
      return Container(width: 30);
    }
    return Image.asset(
      image,
      width: 30,
      height: 30,
    );
  }

  Widget _progress(int index) {
    if (index >= controller.groupList.value.length) {
      return Container();
    }
    int? rate;
    final isLock = controller.groupList.value[index].lockStatus ?? false;
    if (isLock) {
      rate = controller.groupList.value[index].sceneLightRate ?? 0;
    } else {
      rate = controller.groupList.value[index].groupLightRate ?? 0;
    }
    if (rate < 0) {
      return Container(width: 30, height: 30);
    }

    return Container(
      width: 30,
      height: 30,
      margin: EdgeInsets.only(right: 16),
      child: Stack(
        alignment: Alignment.center,
        children: [
          CircularProgressIndicator(
            value: rate / 100,
            strokeWidth: 2,
            backgroundColor: MColor.xFFEEEEEE,
            valueColor: AlwaysStoppedAnimation<Color>(MColor.xFFFFA433),
          ),
          Align(
            alignment: Alignment.center,
            child: Text(
              '$rate%',
              style: MFont.regular10.apply(color: MColor.xFFFFA433),
            ),
          )
        ],
      ),
    );
  }

  get _emptyView {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 12),
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          Get.toNamed(
            Routes.DEVICE_MANAGER,
            arguments: {
              'group': true,
              'add': true,
              'name': LocaleKeys.add_devices_group_title.tr,
            },
          )?.then((value) => controller.refreshAction());
        },
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 32),
          child: Center(
            child: Container(
              width: 64,
              height: 64,
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.2),
                borderRadius: BorderRadius.circular(32),
              ),
              child: Center(child: Image.asset(Assets.imagesListInsert, width: 32, height: 32)),
            ),
          ),
        ),
      ),
    );
  }
}
